<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>使用snabbdom虚拟dom实现更新操作</title>
</head>

<body>
  <div id="app">

  </div>
  <script src="https://lib.baomitu.com/snabbdom/0.7.4/snabbdom.js"></script>
  <script src="https://lib.baomitu.com/snabbdom/0.7.4/snabbdom-style.js"></script>
  <script>
    const obj = {}
    const { init, h } = snabbdom

    // 第一步获取patch函数, 对比两个虚拟dom，执行dom操作
    const patch = init([
      snabbdom_style.default
    ])

    let vnode;  // 保存之前旧的虚拟dom 

    function defineReative(obj, key, val) {
      // 对传入的obj进行访问拦截
      Object.defineProperty(obj, key, {
        get() {
          console.log('get', key)
          return val
        },
        set(newVal) {
          console.log('newVal', newVal)
          if (newVal !== val) {
            val = newVal
            // 更新函数
            update()
          }
        }
      })
    }

    // 使用虚拟dom做更新
    function update() {
      vnode = patch(vnode, h('div#app',{style: {color: 'red'}}, obj.foo))
    }

    defineReative(obj, 'foo', new Date().toLocaleTimeString())
    // 执行函数
    vnode = patch(app, h('div#app', obj.foo))
    console.log('vnode', vnode)


    setInterval(() => {
      obj.foo = new Date().toLocaleTimeString()
    }, 1000)

  </script>
</body>

</html>